<template>
    <div class="rich-text-wrapper">
<!--        <iframe-->
<!--            ref="iframeRef"-->
<!--            class="rich-text-iframe"-->
<!--            frameborder="0"-->
<!--            scrolling="no"-->
<!--        ></iframe>-->
        <div class="rich-text">
            <div class="sand-box" v-html="formatRichText(content)"></div>
        </div>
    </div>
</template>

<script setup>
import {nextTick, onMounted, ref} from 'vue';

const props = defineProps({
    content: {
        type: String,
        default: ''
    }
})

const iframeRef = ref(null);

/**
 * 格式化富文本字符串
 *  1.将 style 中的 height 属性设置为 auto
 *  2.将 style 中的 width 属性设置为 max-width:100%
 *  3.移除 br 标签
 *
 * @param str {string}
 */
function formatRichText(str) {
    str = str.replace(/style="[^"]*width:[^"]+"/gi,
        (style) => {
            style = style.replace(/[;"\s](height:.+?)(?=[;"])/gi,
                (heightStyle, capture) => heightStyle.replace(capture, 'height:auto'))
            style = style.replace(/[;"\s](width:.+?)(?=[;"])/gi,
                (widthStyle, capture) => widthStyle.replace(capture, 'max-width:100%'))

            return style;
        });
    str = str.replace(/<br>/, '');

    return str;
}

// onMounted(() => {
//     const richTextHTML = formatRichText(props.content);
//     const document = iframeRef.value.contentDocument;
//     const head = document.querySelector('head');
//     const body = document.querySelector('body');
//     head.innerHTML = '<meta name="viewport" content="initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">' +
//         '<style>html,body{padding:0;margin:0}img{max-width:100%;height:auto}</style>'
//     body.innerHTML = richTextHTML;
//
//     nextTick(() => (iframeRef.value.style.height = body.scrollHeight + 50 + 'px'));
//
//     // 动态计算内容高度
//     // document.defaultView.addEventListener('resize', (ev) => {
//     //     iframeRef.value.style.height = ev.target.document.body.scrollHeight + 'px';
//     // })
// })

</script>

<style lang="scss">
.rich-text-wrapper {
    background: #FFFFFF;
    height: 100%;
    overflow-y: auto;

    .rich-text-iframe {
        padding: 15px;
        height: auto;
        width: 100%;
    }

    .rich-text {
        padding: 15px;

        img {
            max-width: 100%;
        }
    }

    .sand-box {
        * {
            box-sizing: content-box;
        }
    }
}
</style>